﻿$(function () {
    "use strict";

    var SideTemplate = '<option value="">Side</option><option value="buy">Buy</option><option value="buy_to_cover">Buy to Cover</option><option value="sell">Sell</option><option value="sell_short">Sell Short</option>',
        SideOptionTemplate = '<option value="">Side</option><option value="buy_to_open">Buy to Open</option><option value="buy_to_close">Buy to Close</option><option value="sell_to_open">Sell to Open</option><option value="sell_to_close">Sell to Close</option>',
        MultilegOrderType = '<option value="">Order Type</option><option value="market">Market</option><option value="debit">Debit</option><option value="credit">Credit</option><option value="even">Even</option>',
        OrderTyte = '<option value="">Order Type</option><option value="market">Market</option><option value="limit">Limit</option><option value="stop">Stop</option><option value="stop_limit">Stop Limit</option>';

    var multilegItem = $('.multileg-order-container ul > li:first-child'),
        multilegResultItem = $('.option-result-container .option-result'),
        symbolQuote = null,
        expirations = null,
        strikes = null,
        chains = null;

    $('.option-container').hide();

    $('.btn-equity').click(function () {
        $('.class-field').val($(this).data('value'));
        $('.option-container, .multileg-order-container, .normal-order-container .title, .equity-leg-container').hide();
        $('.normal-order-container').show();

        $('.quantity-container').removeClass('col-sm-3').addClass('col-sm-6');
        $('.side-container').removeClass('col-sm-3').addClass('col-sm-6');

        $('.order-types').empty().append(OrderTyte);
        $('.side-container > select').empty().append(SideTemplate);

        return false;
    });

    $('.btn-option').click(function () {
        $('.class-field').val($(this).data('value'));
        $('.normal-order-container, .option-container').show();
        $('.multileg-order-container, .normal-order-container .title, .equity-leg-container').hide();

        $('.quantity-container').removeClass('col-sm-6').addClass('col-sm-3');
        $('.side-container').removeClass('col-sm-6').addClass('col-sm-3');

        $('.order-types').empty().append(OrderTyte);
        $('.side-container > select').empty().append(SideOptionTemplate);

        return false;
    });

    $('.btn-multileg').click(function () {
        $('.class-field').val($(this).data('value'));
        $('.option-container, .normal-order-container, .normal-order-container .title, .equity-leg-container').hide();
        $('.multileg-order-container').show();

        $('.quantity-container').removeClass('col-sm-3').addClass('col-sm-6');
        $('.side-container').removeClass('col-sm-3').addClass('col-sm-6');

        $('.order-types').empty().append(MultilegOrderType);

        return false;
    });

    $('.btn-combo').click(function () {
        $('.class-field').val($(this).data('value'));
        $('.multileg-order-container, .amount').hide();
        $('.normal-order-container, .option-container, .normal-order-container .title, .equity-leg-container').show();

        $('.quantity-container').removeClass('col-sm-6').addClass('col-sm-3');
        $('.side-container').removeClass('col-sm-6').addClass('col-sm-3');

        $('.order-types').empty().append(MultilegOrderType);
        $('.side-container > select').empty().append(SideOptionTemplate);

        return false;
    });

    $('.btn-preview').click(function () {
        var values = {
            account_id: $('.accounts').val(),
            class: $('.class-field').val(),
            symbol: $('.symbol').val(),
            duration: $('.duration').val(),
            side: $('.side').val(),
            quantity: $('.quantity').val(),
            type: $('.order-types').val(),
            price: $('.price').val(),
            stop: $('.stop').val(),
            amount: $('.amount').val(),
            option_symbol: $('.option-field').val(),
            comboEquitySide: $('.equity-side').val(),
            comboEquityQuantity: $('.equity-quantity').val()
        };

        if (values.class == 'multileg') {
            appendMultilegParams(values);
            $('.multileg-params').val(values.multilegParams);
        }

        $.ajax({
            url: "Service.asmx/PreviewOrder",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify({
                order: values
            }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.d && data.d.length != 0) {
                    try {
                        var result = JSON.parse(data.d),
                            order = result.order,
                            errors = result.errors;

                        if (errors) {
                            $('.messages').show();
                            $('.messages .error').text(errors.error);
                            return;
                        }

                        $('.preview-order-result').show();
                        $('.preview-order-result .commission').text(order.commission);
                        $('.preview-order-result .totalcost').text(order.cost);

                        $('.btn-submit-order').removeAttr('disabled');
                    } catch (e) {
                        $('.messages').show();
                        $('.messages .error').text(data.d);
                    }
                }
            },
            error: function (result) {
            }
        });

        return false;
    });

    $('.search-button').click(function (e) {
        var symbol = $('.search-box').val();
        $('.symbol-result').hide();
        $('.messages').hide();
        if (symbol.length != 0) {
            $.ajax({
                url: "Service.asmx/GetQuotes",
                dataType: "json",
                type: 'POST',
                data: JSON.stringify({
                    criteria: symbol
                }),
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    if (data.d && data.d.length != 0) {
                        try {
                            var quotes = JSON.parse(data.d).quotes,
                                quote = quotes.quote;

                            if (quotes.unmatched_symbols) {
                                alert('Wrong symbol');
                                return;
                            }

                            symbolQuote = quote;

                            $('.symbol-result').show();
                            $('.symbol-result .name').text(symbol + ' - ' + quote.description);
                            $('.symbol-result .last').text(quote.last);
                            $('.symbol-result .change').text(quote.change);
                            $('.symbol-result .bid').text(quote.bid + ' x ' + quote.bidsize);
                            $('.symbol-result .ask').text(quote.ask + ' x ' + quote.asksize);

                            var orderType = $('.class-field').val();
                            if (orderType == "option" || orderType == "combo") {
                                getExpirationDate(symbol);
                            } else if (orderType = 'multileg') {
                                getExpirationDate(symbol, true);
                            }
                        } catch (e) {
                            $('.messages').show();
                            $('.messages .error').text(data.d);
                        }
                    }
                },
                error: function (result) {
                }
            });
        }

    });

    $('.multileg-order-container ul').delegate('.multileg-item-add', 'click', function () {
        $('.multileg-order-container ul').append(multilegItem.clone());
        return;
    });

    $('.multileg-order-container ul').delegate('.multileg-item-del', 'click', function () {
        if ($('.multileg-order-container ul > li').length == 1) {
            return;
        }
        $('.multileg-order-container ul > li:last-child').remove();
        return;
    });

    $('.order-types').change(function (e) {
        var limitContainer = $('.limit-container'),
            stopContainer = $('.stop-container'),
            amountContainer = $('.amount-container'),
            selectedItemValue = $(this).val();

        limitContainer.hide();
        stopContainer.hide();
        amountContainer.hide();

        $('input[name=price]', limitContainer).val('');
        $('input[name=stop]', stopContainer).val('');
        $('input[name=amount]', amountContainer).val('');

        switch (selectedItemValue) {
            case 'limit':
                limitContainer.show();
                break;
            case 'stop':
                stopContainer.show();
                break;
            case 'stop_limit':
                limitContainer.show();
                stopContainer.show();
                break;
            case 'debit':
            case 'credit':
                amountContainer.show();
                break;
            default:
                limitContainer.hide();
                stopContainer.hide();
                break;
        }
    });

    $('.multileg-order-container').delegate('.multileg-cp-field', 'change', function () {
        var parent = $(this).parents('.item');
        var strike = $('.multileg-strikes', parent);
        var date = $('.multileg-expiration', parent).val();
        if (strike) {
            getChains(symbolQuote.symbol, date, strike, $(this).val());
        }
    });

    $('.cp-field').change(function () {
        var strike = $('.strikes').val();
        var date = $('.expiration').val();
        if (strike) {
            getChains(symbolQuote.symbol, date);
        }
    });

    var getExpirationDate = function (symbol, isMultileg) {
        $.ajax({
            url: "Service.asmx/GetExpirationDates",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify({
                symbol: symbol
            }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.d && data.d.length != 0) {
                    var expirationsData = JSON.parse(data.d).expirations;
                    if (expirationsData != null && expirationsData.date != null) {
                        var options = "<option value=''>Expiration</option>";
                        $.each(expirationsData.date, function (index, item) {
                            options += "<option value='" + item + "'>" + item + "</option>";
                        })

                        if (isMultileg) {
                            $('.multileg-expiration').html(options).removeAttr('disabled');
                            $('.multileg-order-container').delegate('.multileg-expiration', 'change', function () {
                                var target = $(this);
                                getStrikes(symbol, target.val(), target);
                            });
                        } else {
                            $('.expiration').html(options).removeAttr('disabled');
                            $('.expiration').change(function () {
                                getStrikes(symbol, $(this).val());
                            });
                        }
                    }
                }
            },
            error: function (result) {
            }
        });
    };

    var getStrikes = function (symbol, date, currentExpiration) {
        $.ajax({
            url: "Service.asmx/GetStrikes",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify({
                symbol: symbol,
                date: date
            }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.d && data.d.length != 0) {
                    var strikesData = JSON.parse(data.d).strikes;
                    if (strikesData != null && strikesData.strike != null) {
                        var options = "<option value=''>Strikes</option>";
                        $.each(strikesData.strike, function (index, item) {
                            options += "<option value='" + item + "'>" + item + "</option>";
                        })

                        if (currentExpiration) {
                            var parent = currentExpiration.parents('.item');
                            $('.multileg-strikes', parent).html(options).removeAttr('disabled');

                            parent.delegate('.multileg-strikes', 'change', function () {
                                getChains(symbol, date, $(this));
                            });
                        } else {
                            $('.strikes').html(options).removeAttr('disabled');
                            $('.strikes').change(function () {
                                getChains(symbol, date);
                            });
                        }
                    }
                }
            },
            error: function (result) {
            }
        });
    };

    var getChains = function (symbol, date, multilegStrike, multilegOptionType) {
        $.ajax({
            url: "Service.asmx/GetChain",
            dataType: "json",
            type: 'POST',
            data: JSON.stringify({
                symbol: symbol,
                date: date
            }),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.d && data.d.length != 0) {
                    var chainsData = JSON.parse(data.d).options;
                    if (chainsData != null && chainsData.option != null) {
                        chains = chainsData.option;
                        var strike = multilegStrike ? multilegStrike.val() : $('.strikes').val();
                        var optionType = multilegOptionType || $('.cp-field').val();
                        $.each(chains, function (index, item) {
                            if (item.strike == strike && item.option_type == optionType) {
                                if (multilegStrike) {
                                    //check option result exist, if true -> update data, otherwise create new item
                                    var resultItem;
                                    $('.option-result-container .option-result').each(function (index, value) {
                                        if ($(value).data('symbol') == item.symbol) {
                                            resultItem = $(value);
                                            return;
                                        }
                                    });

                                    if (!resultItem) {
                                        resultItem = multilegResultItem.clone();
                                        resultItem.data('symbol', item.symbol);
                                    }

                                    $('.multileg-option-symbol', multilegStrike.parents('.item')).val(item.symbol);
                                    $('.description', resultItem).html(item.description);
                                    $('.bid', resultItem).html(item.bid);
                                    $('.ask', resultItem).html(item.ask);
                                    $('.option-result-container').append(resultItem.show());
                                } else {
                                    $('.option-result').show();
                                    $('.option-result .description').html(item.description);
                                    $('.option-result .bid').html(item.bid);
                                    $('.option-result .ask').html(item.ask);
                                    $('.option-field').val(item.symbol);
                                }
                                return false;
                            }
                        });
                    }
                }
            },
            error: function (result) {
            }
        });
    };

    var appendMultilegParams = function (params) {
        if ($('.class-field').val() == 'multileg') {
            var param = '';
            $('.multileg-order-container ul li').each(function (index, item) {
                var item = $(item);
                var multilegSide = $('.multileg-side', item).val();
                var multilegQuantity = $('.multileg-quantity', item).val();
                var multilegOptionSymbol = $('.multileg-option-symbol', item).val();

                param += '&side[' + index + ']=' + multilegSide + '&quantity[' + index + ']=' + multilegQuantity + '&option_symbol[' + index + ']=' + multilegOptionSymbol;
            });
            params.multilegParams = param;
        }
    };
});